package com.wang.weblog.admin.service.impl;

import com.wang.weblog.admin.service.AdminFileService;
import com.wang.weblog.common.enums.ResponseCodeEnum;
import com.wang.weblog.common.exception.BizException;
import com.wang.weblog.common.utils.AliOssUtil;
import com.wang.weblog.common.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

@Service
@Slf4j
public class AdminFileServiceImpl implements AdminFileService {
    @Resource
    private AliOssUtil aliOssUtil;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @Override
    public Response uploadFile(MultipartFile file) {

        String originalName = file.getOriginalFilename();
        String extension = originalName.substring(originalName.lastIndexOf("."));
        String objectName = UUID.randomUUID() + extension;
        try {
            String fileName = aliOssUtil.upload(file.getBytes(), objectName);
            return  Response.success(fileName);
        } catch (IOException e) {
            log.error("==> 上传文件至 AliOSS 错误: ", e);
            // 手动抛出业务异常，提示 “文件上传失败”
            throw new BizException(ResponseCodeEnum.FILE_UPLOAD_FAILED);
        }

    }
}
